import { BaseStore } from './BaseStore.js';

/**
 * LocalStorage 封装类
 * 提供对 localStorage 的统一操作接口
 */
class LocalStore extends BaseStore {
  constructor(prefix = 'app') {
    super(prefix);
    this.storage = window.localStorage;
    // this.available = this.checkAvailability();
    this.isAsync = false; // LocalStorage 是同步的
  }

  /**
   * 检查 localStorage 是否可用
   * @returns {boolean} 是否可用
   */
  isAvailable() {
    try {
      const test = '__localStorage_test__';
      localStorage.setItem(test, test);
      localStorage.removeItem(test);
      return true;
    } catch (error) {
      console.warn('localStorage is not available:', error);
      return false;
    }
  }

  /**
   * 设置值到 localStorage
   * @param {string} key 键名
   * @param {any} value 值
   * @param {Object} options 选项 (暂时保留，用于未来扩展)
   */
  set(key, value, options = {}) {
    if (!this.storage) {
      console.warn('localStorage is not available');
      return false;
    }

    try {
      const serializedValue = this.serialize(value);
      const storageKey = this.getKey(key);
      
      // 如果需要设置过期时间
      if (options.expires) {
        const expiresAt = Date.now() + options.expires;
        const dataWithExpiry = {
          value: serializedValue,
          expiresAt
        };
        this.storage.setItem(storageKey, JSON.stringify(dataWithExpiry));
      } else {
        this.storage.setItem(storageKey, serializedValue);
      }
      
      return true;
    } catch (error) {
      console.error('Failed to set localStorage item:', error);
      return false;
    }
  }

  /**
   * 从 localStorage 获取值
   * @param {string} key 键名
   * @param {any} defaultValue 默认值
   * @returns {any} 存储的值或默认值
   */
  get(key, defaultValue = null) {
    if (!this.storage) {
      return defaultValue;
    }

    try {
      const storageKey = this.getKey(key);
      const item = this.storage.getItem(storageKey);
      
      if (item === null) {
        return defaultValue;
      }

      // 尝试解析带过期时间的数据
      try {
        const parsed = JSON.parse(item);
        if (parsed && typeof parsed === 'object' && 'expiresAt' in parsed) {
          if (Date.now() > parsed.expiresAt) {
            this.remove(key);
            return defaultValue;
          }
          return this.deserialize(parsed.value);
        }
      } catch (e) {
        // 如果不是带过期时间的数据，继续正常处理
      }

      return this.deserialize(item);
    } catch (error) {
      console.error('Failed to get localStorage item:', error);
      return defaultValue;
    }
  }

  /**
   * 从 localStorage 删除值
   * @param {string} key 键名
   */
  remove(key) {
    if (!this.storage) {
      return false;
    }

    try {
      const storageKey = this.getKey(key);
      this.storage.removeItem(storageKey);
      return true;
    } catch (error) {
      console.error('Failed to remove localStorage item:', error);
      return false;
    }
  }

  /**
   * 清空所有带前缀的 localStorage 项
   */
  clear() {
    if (!this.storage) {
      return false;
    }

    try {
      const keysToRemove = [];
      for (let i = 0; i < this.storage.length; i++) {
        const key = this.storage.key(i);
        if (key && key.startsWith(this.prefix + '_')) {
          keysToRemove.push(key);
        }
      }
      
      keysToRemove.forEach(key => this.storage.removeItem(key));
      return true;
    } catch (error) {
      console.error('Failed to clear localStorage:', error);
      return false;
    }
  }

  /**
   * 检查键是否存在
   * @param {string} key 键名
   * @returns {boolean} 是否存在
   */
  has(key) {
    if (!this.storage) {
      return false;
    }

    const storageKey = this.getKey(key);
    return this.storage.getItem(storageKey) !== null;
  }

  /**
   * 获取所有带前缀的键名
   * @returns {Array<string>} 键名数组
   */
  keys() {
    if (!this.storage) {
      return [];
    }

    const keys = [];
    const prefixWithUnderscore = this.prefix + '_';
    
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i);
      if (key && key.startsWith(prefixWithUnderscore)) {
        keys.push(key.substring(prefixWithUnderscore.length));
      }
    }
    
    return keys;
  }

  /**
   * 获取存储大小（字节）
   * @returns {number} 存储大小
   */
  getSize() {
    if (!this.storage) {
      return 0;
    }

    let size = 0;
    const prefixWithUnderscore = this.prefix + '_';
    
    for (let i = 0; i < this.storage.length; i++) {
      const key = this.storage.key(i);
      if (key && key.startsWith(prefixWithUnderscore)) {
        const value = this.storage.getItem(key);
        size += key.length + (value ? value.length : 0);
      }
    }
    
    return size;
  }
}

// 创建默认实例
export const localStore = new LocalStore();

// 导出类供自定义使用
export { LocalStore };